iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Software Development

從零開始學 Python系列 第 16

Day 16 – 字串搜尋與迴圈練習:統計與找字串

  • 分享至 

  • xImage
  •  

今天的學習重點

  • in、find()、count():字串搜尋
  • 搭配 for 迴圈做文字統計
  • exercise:文字分析工具

一、判斷字串是否存在

最簡單的方式就是用 in:

text = "I love cherry"
print("cherry" in text)    # True
print("apple" in text)      # False

二、找出字串位置 – find()

find() 會回傳 子字串第一次出現的索引位置,找不到會回傳 -1

text = "hello world"
print(text.find("world"))   # 6
print(text.find("apple"))    # -1

三、統計字串出現次數 – count()

count() 會計算某個字串在全文中出現的次數

text = "banana"
print(text.count("a"))   # 3
print(text.count("na"))  # 2

四、字串遍歷與迴圈應用

可以用 for 迴圈逐字檢查或處理字串

text = "hello"
for char in text:
    print(char)

輸出:

h
e
l
l
o

exercise: 統計文章中的字數

article = "When he saw the monster, he screamed!"
word = "monster"

count = article.count(word)
print(f"'{word}' 出現了 {count} 次")

螢幕擷取畫面 2025-08-18 153715

exercise 2: 找出母音的數量

text = "Once upon a time"
vowels = "aeiou"
count = 0

for char in text.lower():
    if char in vowels:
        count += 1

print("母音數量:", count)

螢幕擷取畫面 2025-08-18 154054

學習心得

今天練習用 find() 精準定位字串的位置、用 count() 快速統計次數,搭配 for 迴圈更能自己寫出條件判斷的邏輯。
明天要學 try / except 例外處理,讓程式在遇到錯誤時不會直接當掉,而是能優雅地處理問題,提升程式的穩定性與可靠性!


上一篇
Day 15 – 字串處理:split、replace、format、f-string
下一篇
Day 17 – try / except 例外處理:讓程式更穩健
系列文
從零開始學 Python30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言